import csv
import json
import requests


def parse(i):
    url = 'https://iftp.chinamoney.com.cn/ags/ms/cm-u-bond-md/BondMarketInfoListEN'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36'}

    # 确定要传入的表单数据参数,bondType：100001表示的是Treasury Bond的代码号
    data = {'pageNo': i, 'pageSize': 15, 'bondType': 100001, 'issueYear': 2023}

    # 研究网站发现，使用的是通常的表单提交post请求
    response = requests.post(url, headers=headers, data=data)
    re_data = json.loads(response.text)
    # 解析返回表格数据，列名包括ISIN, Bond Code, Issuer, Bond Type, Issue Date, Latest Rating
    resultList = re_data['data']['resultList']
    data_list = []
    for i in resultList:
        ISIN = i['isin']
        Bond_Code = i['bondCode']
        Issuer = i['entyFullName']
        Bond_Type = i['bondType']
        Issue_Date = i['issueStartDate']
        Latest_Rating = i['inptTp']
        data_list.append([ISIN, Bond_Code, Issuer, Bond_Type, Issue_Date, Latest_Rating])
    save(data_list)


def save(data):
    with open('data.csv', mode='a', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(['ISIN', 'Bond_Code', 'Issuer', 'Bond_Type', 'Issue_Date', 'Latest_Rating'])
        writer.writerows(data)


if __name__ == '__main__':
    for i in range(1, 4):
        parse(i)
